let str
let Cookieid
let localId
let id
if(Cookies.get("user")){
   str= JSON.parse(Cookies.get("user"))
   Cookieid=str.id
   id=Cookieid
}else{
  localId=localStorage.getItem("id")
  id=localId
}



// let id= localId||Cookieid
console.log(id);

// 登录
let log=document.querySelector(".login")
log.onclick=function(){
  location.href="../html/login.html"
}
// 注册
let reg=document.querySelector(".reg")
reg.onclick=function(){
  location.href="../html/login.html"
}
// 跳转到自己
let self=document.querySelector(".headerImg")
self.onclick=function(){
  location.href="../index.html"
}
let token=localStorage.getItem("token")
let loginBox=document.querySelectorAll(".login-header")
let loginIfo=document.querySelector(".info")
let outInfo=document.querySelector(".out")

function autoLogin(){
  
  console.log(loginBox);
  console.log(token);
  if(token||Cookies.get("user") != null){
    loginBox[0].style.display="none"
    loginBox[1].style.display="block"
    let coo=Cookies.get("user")
    if(coo!=null){
      let str = JSON.parse(coo);
      console.log(str);
      console.log(str.username);
      let ustr=str.username
      loginIfo.innerHTML=`欢迎亲爱的 `+ustr
    }else{
      let ustr=localStorage.getItem("username");
      loginIfo.innerHTML=`欢迎亲爱的 `+ustr
    }
  }

}
autoLogin()

outInfo.onclick=function(){
  if(Cookies.get("user")!=null){
    let str = JSON.parse(Cookies.get("user"));
    Cookies.set("user", str, { expires: 0 }); 
 }
 if(localStorage.getItem("id")){
    localStorage.clear()
 }
  loginBox[1].style.display="none"
  loginBox[0].style.display="block"
}
// 
let nav=document.querySelectorAll(".navA a")
current=0;

nav.forEach(function(v,i){
    
  nav[i].classList.remove("nav-active");
  v.onclick=function(){
    nav[current].classList.remove("nav-active");
    nav[i].classList.add("nav-active");
    if(i==0){
      location.href="../index.html"
    }
    current=i;
}
})
console.log(id);

let productArr=[];
let tishi=document.querySelector(".tishi")
// 全选选择框
let allCkBtn = document.querySelector(".check-all")
let thead=document.querySelector(".thead")
let foot=document.querySelector(".foot")
console.log(id);
 async function loadList(){
    let obj=await axios.get(carList, { params: { id:138133 } })
    productArr = [...obj.data.data]
    if(productArr.length>0){
      foot.style.display="block"
      thead.style.opacity="1"
    }else{
      tishi.style.display="block"
      thead.style.opacity="0"


    }
    console.log(productArr);
    let sum="0.00"
    let num="0"
    rendFoot(sum,num)
    rendList()   
    console.log(allCkBtn);
    allCkBtn.checked = false; 
  }


function rendList(){
  let tbody=document.querySelector(".tbody")
  let str=productArr.map((v)=>{
    // console.log(v.pimg);
    let str = `<input type="checkbox" name=""  class="singleck" onchange="singleCKChange(${v.pid},this)">`
    if (v.checked) {
      str = `<input type="checkbox" name=""  checked class="singleck" onchange="singleCKChange(${v.pid},this)">`
    }
      return `
      <tr>
      <td class="checkbox">
        ${str}
      </td>
      <td class="goods">
        <img src="${v.pimg}" alt="" /><span>${v.pname}</span>
      </td>
      <td class="price">${v.pprice}</td>
      <td class="count">
        <span class="reduce" onclick="deupdste(${v.pid},this)">-</span>
        <input class="count-input" type="text" value="${v.pnum}" />
        <span class="add" onclick="addupdste(${v.pid},this)">+</span>
      </td>
      <td class="subtotal">${(v.pprice*v.pnum).toFixed(2)}</td>
      <td class="operation">
        <span class="delete" onclick="del(${v.pid})">删除</span>
      </td>
    </tr>
      `
  })
  tbody.innerHTML=str.join("")
 
}
// 判断uid如果存在跳转购物车，不存在跳转到登录页

if(id||Cookies.get("user") != null){
  loadList()
}else{
  alert("请到登录页登录！")
  location.href="../html/login.html"
}

// 删除单个商品
async function del(pid) {
  let info=await axios.get(carDel, { params: { uid: id, pid } })
    let sum="0.00"
    let num="0"
    rendFoot(sum,num)
    console.log(productArr.length);
    if(productArr.length < 2){
      foot.style.display="none"
    }
    loadList()
  
}
let uid=localStorage.getItem("id")

// 添加数量
async function addupdste(pid,btn){
  let numInput=btn.parentNode.querySelector(".count-input")
  let pnum=parseInt(numInput.value)
  pnum++;

  let res = await axios.get(pnumAPI, { params: { uid:id, pid, pnum } })
  console.log(res);
  
  let arr=productArr.find(((v)=>v.pid==pid))
  // arr.pnum=pnum
  numInput.value=pnum
  loadList()
  price(productArr)
}
// 减少数量
async function deupdste(pid, btn) {
  let numInput=btn.parentNode.querySelector(".count-input")
  let pnum = parseInt(numInput.value)
  pnum--;
  if (pnum < 1) {
    let re = confirm("已经达到商品最小值，是否需要删除该商品？")
    console.log(re);
    numInput.value = 1;
    if (re == true) {
      // 删除商品小于1的选项
      axios.get(carDel, { params: { uid: id, pid } }).then((r) => {
        console.log(r.data);
        loadList()
      })
    } else {
      return;
    }
  } else {
    numInput.value = parseInt(pnum)
  }
  let res = await axios.get(pnumAPI, { params: { uid, pid, pnum } })
  console.log(res);
  price(productArr)
  loadList()

}
// 全选状态
function allChecked(allCkBtn) {
  console.log(allCkBtn.checked);
  productArr.forEach((v) => v.checked = true)
  productArr.forEach((v) => v.checked = allCkBtn.checked)
  document.querySelectorAll(".singleck").forEach((v) => v.checked = allCkBtn.checked)
  price(productArr)
}
// 单个商品的选框=> 有其中一个取消，就取消全选状态
function singleCKChange(pid, singleck) {

  // 更新选中的单个商品选框的状态
  let ckArr =  productArr.find((v) => v.pid == pid)
  // 将当前选框的状态重新进行绑定，绑定为自身的选择状态
  ckArr.checked = singleck.checked

  // 当所有商品选中时，全选按钮才会选中
  let allCkArr =  productArr.every((v) => v.checked == true)
  // 则全选框的选中状态取决于遍历后的返回结果true/false 
  let all
  all = allCkArr;
  allCkBtn.checked=all;
  if(singleck.checked==false){
    let sum="0.00"
    let num="0"
    rendFoot(sum,num)
  }
  price(productArr)
  
}
// 计算商品单价和总价
function price(arr){
  let isselect = arr.filter((v) => v.checked == true);

  console.log("选中了" + isselect.length);

  // 计算所选商品单行总价
  let countArr = isselect.map((v)=>v.pnum*v.pprice)
  console.log(countArr);
  // 累加价格
  let sum
  if(countArr.length>0){

   sum =countArr.reduce((prevs,next)=>prevs+next)

  }else{
    sum="0.00"
  }

  let summoney=sum.toFixed(2)
  console.log(sum);
  let num=isselect.length
  rendFoot(summoney,num)
}
let footmath=document.querySelector(".footMath")
function rendFoot(sum,num){
  let str=`
  <input type="hidden" id="cartTotalPrice" />
  <div class="fr total">合计：￥ <span id="priceTotal"> ${sum} </span></div>
  <div class="fr selected" id="selected">已选商品 <span id="selectedTotal"> ${num} </span> 件</div>`
  footmath.innerHTML=str
}

let delAll=document.querySelector("#deleteAll")
delAll.onclick=async function(){
  console.log("12345");
  if(allCkBtn.checked){
    productArr.forEach((v)=>{
      let pid = v.pid;
      let obj=axios.get(carDel, { params: { uid: id, pid } });
      foot.style.display="none"
    })
    loadList()
  }else{
    alert("选中所有商品后才能删除！")
  }
}
let acheck=document.querySelector(".allch")

let toTop=document.querySelector(".toTop")
toTop.onclick=function(){
  document.documentElement.scrollTo({top:0,behavior:"smooth"})
}

window.onscroll =  function () {
  console.log(document.documentElement.scrollTop);
  if (document.documentElement.scrollTop >= 99) {
    toTop.style.display="block";
    } else{
    toTop.style.display="none"
  }
}
